// 引入net模块
const net = require("net");

const port = 3000;
const host = "127.0.0.1";

const server = net.createServer((socket) => {
	// 2. 等待连接,连接后触发 socket(Buffer)
	console.log("2. server is connected to" + socket);

	// 3. 收到client.js 的data请求
	socket.on("data", (data) => {
		console.log("3. server get client data: ", data.toString());
		// 写入并返回
		socket.write("this is server");
	});

  // 客户端关闭触发
	socket.on("end", function () {
		console.log("4. 客户端关闭连接");
	});

  // 服务端关闭触发
	socket.on("close", () => {
		console.log("5. server is close");
	});
});

// 1. 开启服务
server.listen(port, host, () => {
	console.log("1. server is running");
});
